package com.bargate.domain.spring.expression.value;

import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: EAD-MASTER
 * Date: 04/10/2010
 * Time: 00:31:32
 * To change this template use File | Settings | File Templates.
 */
public class FunctionRegistrationOperations {
    SpelExpressionParser parser = new SpelExpressionParser();

    public void registerCustomFunction1() {
        StandardEvaluationContext context = new StandardEvaluationContext();

        try {
            context.registerFunction("stripExt", StringUtils.class.getDeclaredMethod("stripFilenameExtension", new Class[]{String.class}));
            String value = parser.parseExpression("#stripExt('filename.jpg')").getValue(context, String.class);
            System.out.println("value = " + value);
        } catch (NoSuchMethodException e) {
            System.out.println("error finding method : " + e.getMessage());
        }
    }

    public void testRegisterFunction2() {
        List<Integer> list = new ArrayList<Integer>(Arrays.asList(0, 1, 24, 5, 56, 4, 112, 41, 17));
        StandardEvaluationContext context = new StandardEvaluationContext();
        try {
            context.registerFunction("max", Collections.class.getDeclaredMethod("max", new Class[]{Collection.class}));
        } catch (NoSuchMethodException e) {
            System.out.println("error finding method : " + e.getMessage());
        }
        context.setRootObject(list);
        Integer max = parser.parseExpression("#max(#root)").getValue(context, Integer.class);
        System.out.println("max = " + max);
    }


    public static void main(String[] args) {
        FunctionRegistrationOperations registrationOperations = new FunctionRegistrationOperations();
        registrationOperations.registerCustomFunction1();
        registrationOperations.testRegisterFunction2();
    }
}
